<!DOCTYPE html>
<html>
<head>
<include file='Common:header' />
<include file='Common:codemirror' />
<script type="text/javascript">
var output = '';
var i = 1;
var runcode = function () {
	var code = editor.getValue();
	if (localStorage['lastst']) {//如果存在最新片段，进行比较
		if (localStorage[localStorage['lastst']] != code) {//如果最新片段和编辑器的片段不相同，则保存编辑器的到最新片段，并更新lastst
			var count = +localStorage['fragcount'];//top数值,并转换为number类型
			var oldest = +localStorage['cursor'].slice(5);//bottom数值,并转换为number类型
			localStorage['frag_' + count] = code;
			localStorage['lastst'] = 'frag_' + count;//更新last记录的key
			li.after("<li onclick='getCode(this)' class='frag_" + count + "'><a>" + 'frag_' + i + "</a></li>");
			i++
			if (count - oldest > 9) {//检查以存储的片段队列长度:top-bottom
				//删除最早的队列
				localStorage.removeItem('frag_' + oldest);
				//删除菜单中的条目
				$('#codelist').find('.frag_' + oldest).remove();
				//更新最早的队列
				localStorage['cursor'] = 'frag_' + (1 + oldest);
			}
			localStorage['fragcount'] = 1 + count;
		}
	} else {
		//首次访问时，创建fragcode本地存储值,fragcount队列计数器
		localStorage['frag_0'] = code;
		localStorage['fragcount'] = 1;
		localStorage['cursor'] = 'frag_0';//cursor记录最早的片段的key
		localStorage['lastst'] = 'frag_0';//last记录最后的片段的key
		li.after("<li onclick='getCode(this)' class='frag_0'><a>" + 'frag_' + i + "</a></li>");
		i++;
	}
	$.post("__APP__/Tool/fragmentTest", {code:editor.getValue()}, function (data, status) {
		if (status == 'success') {
			if (data != output) {
				if (/<head>/.test(data)) {
					output = data.replace(/[\r\n]/mg, '').replace(/<head>.*<\/head>/, '').replace(/class="content"/, '');
				} else {
					output = data;
				}
			}
			//将输出放置到console窗口内
			var a = $('.text-html');
			if (a.hasClass('active')) {
				a.removeClass('active');
				convertOutput(a.get(0));
				a.addClass('active');
			} else {
				a.addClass('active');
				convertOutput(a.get(0));
				a.removeClass('active');
			}
		}
	})
};
//输出窗口的内容在div和textarea间转换
var convertOutput = function (obj) {
	var width = $('.console').outerWidth() - 20;
	if ($(obj).hasClass('active')) {
		$('#output').replaceWith("<textarea id='output' readonly class='output-text' style='width: " + width + "px ;'>" + output + "</textarea>")
	} else {
		$('#output').replaceWith("<div id='output' class='output-html' style='width: " + width + "px ;'>" + output + "</div>")
	}
};
//点击菜单的‘最近运行代码’将代码放入编辑器
var getCode = function (obj) {
	var thecode = localStorage[$(obj).attr('class')];
	editor.setValue(thecode)
};
//重设编辑器内的内容
var resetValue = function () {
	editor.setValue('\<\?php\n')
};
//标点替换
var refactCode = function () {
	var code = editor.getValue();
	if (typeof code == 'string') {
		code = code.replace(/[“”″ʺ˝ˮ‶‟〝〞]/g, '"');
		code = code.replace(/[’‘‛❛❜]/g, "'");
		code = code.replace(/[‚，ˏ͵]/g, ",");
		code = code.replace(/[（❨❪﴾]/g, "(");
		code = code.replace(/[）﴿❫❩]/g, ")");
		code = code.replace(/[；﹔︔]/g, ";");
		code = code.replace(/[：˸܃᠄﹕]/g, ':');
		code = code.replace(/。/g, '.');
		code = code.replace(/？/g, '?');
		code = code.replace(/[  ]/g, ' ');
		code = code.replace(/[–—‒﹘]/g, '-');
		editor.setValue(code);
	}
}
//常用代码
var codesnippts = function (itemnum) {
	if (codelist[itemnum]) {
		editor.setValue(codelist[itemnum]);
	}
}
var codelist=[];

$(function () {
	$('body').on('keydown',function(e){
		if(e.ctrlKey) {
			var consolediv=$('.console');
			switch (e.keyCode) {
				case 37:
					consolediv.animate({height:['+=100', 'swing']}, 200);
					break;
				case 39:
					consolediv.animate({height:['-=100', 'swing']}, 200);
					break;
				case 13:
					$('.runcode').trigger('click');
					break;
			}
		}
	});
	//获取代码片段数据
	$.post('__APP__/FileManager/sendxml',{file:'codelist'},function(data,status){
		if (status == 'success') {
			var menu=$(data).find('menu').children('ul').clone();
			if (menu) {
				$('.codelist').append(menu);
				var items = $($.parseXML(data)).find('item');
				$.each(items, function (key, val) {
					codelist[parseInt($(val).attr('num'))] = $.trim($(val).text());
				})
			}
		}
	})

	$('#help').popover({
		placement:'right',
		trigger  :'hover',
		title    :'输出格式',
		content  :'html格式下标签会解析；\ntext格式则原样显示，text格式输出\\t和\\n可进行Tab缩进和换行。'
	})
	$('.refactCode').tooltip({placement:'top'});
	//在菜单列出最近运行的代码
	window.li = $('#lastst');
	$.each(localStorage, function (k, val) {
		if (localStorage.key(k).substr(0, 5) == 'frag_') {
			li.after("<li onclick='getCode(this)' class='" + localStorage.key(k) + "'><a>" + 'frag_' + i + "</a></li>");
			i++;
		}
	})

	//拖动调整console窗口大小
	var mousestatus;
	$(document).on({
		'mouseup'  :function () {
			mousestatus = 0;
			$(window).off('selectstart');
		},
		'mousemove':function (e) {
			if (mousestatus === 1) {
				$('.console').css('height', $(window).outerHeight() - e.clientY);
				$('#output').css('height', $(window).outerHeight() - e.clientY - 44);//44是output的上下padding之和加magin-bottom和dragbar的高度再加2px
			}
		}
	});
	$('.drag_bar').on({
		'mousedown':function () {
			mousestatus = 1;
			$(window).on('selectstart', function () {
				return false;
			});
		},
		'dragstart':function () {
			return false;
		}
	});
});
</script>
<style type="text/css">
	#output {
		height: 100%;
		padding: 12px 20px;
		color: #fff;
		min-height: 20px;
		border: 0;
		border-radius: 0;
		box-shadow: none;
		background: transparent;
		opacity: 0.96;
		overflow: auto;
		word-break: break-all;
		word-wrap: break-word;
		font-family: monospace, "Helvetica Neue", Helvetica, Arial, sans-serif;
	}

	#output pre {
		color: inherit;
		padding: 0;
		margin: 0;
		background: transparent;
		border: 0;
		border-radius: 0;
	}

	.console-body {
		bottom: 0;
		width: 100%;
		z-index: 2100;
	}

	.console {
		max-height: 600px;
		min-height: 10px;
		width: 100%;
		background: #27254B;
		overflow-y: auto;
		overflow-x: hidden;
		opacity: 0.9;
		/*bottom: 0;*/
		/*z-index: 100;*/
	}

	.drag_bar {
		height: 8px;
		background: #d2d2d2;
		cursor: row-resize;
	}

	.console .error .info .title h3 {
		color: inherit;
	}
	.popover-content {
		font-size: 14px;
		white-space: pre-wrap;
	}
	#codelist {
		background-color: #ffffff;
		border-radius: 4px;
	}

	#codelist .nav-header {
		padding: 0;
		font-size: 14px;
	}

	#codelist li:first-child > a {
		background: #52659E;
		color: white;
	}
</style>
</head>
<body>
<include file='Common:navbar' />

<div class="container content">
	<div class="row body-content">
		<div class="span3">
			<include file="Common:leftbar" />
			<ul class="nav nav-tabs nav-stacked" id="codelist" style="margin-top: 10px;">
				<li id="lastst" class="nav-header"><a>最近运行的片段</a></li>

			</ul>
		</div>
		<div class="span9">
			<div class="">
				<div class="alert alert-info">撤销：Ctrl+Z | 重做：Ctrl+Y | 全屏: F11 <br/>升高console：Ctrl+Left | 降低console：Ctrl+right | 运行：Ctrl+Enter</div>
				<div class="btn-group" style="float: right;">
					<input type="button" value="运行代码" class="btn btn-primary runcode" onclick="runcode()">
				</div>

				<div class="btn-group codelist">
					<button type="reset" value="清空代码" class="btn btn-primary" onclick="editor.setValue('\<\?php\n')">清空代码</button>
					<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
						<span class="caret"></span>
					</button>

				</div>
				<div class="btn-group">
					<input type="button" value="格式化所选代码" class="btn btn-primary" onclick="autoFormatSelection()">
					<input type="button" value="标点转换" class="btn btn-primary refactCode" onclick="refactCode()"  data-original-title="将标点等转为英文格式的符号">

					<input type="button" id="help" class="btn btn-primary text-html" data-toggle="button" onclick="convertOutput(this)" value="HTML输出">HTML
				</div>
				<div style="border: 1px solid #ebebeb;margin: 20px 0;">
					<textarea name="code-editor" id="code-editor" style="display: none;">&lt;?php echo "hello world";</textarea>
				</div>
			</div>
		</div>
	</div>
</div>
<div class="affix console-body">
	<div class="drag_bar"></div>
	<div class="console" style="width: 100%;">
		<textarea id="output" class="output-text" readonly style="width: 100%;">&gt; 还没有任何输出....</textarea>
	</div>
</div>

<{$footer}>
</body>
</html>
